break and next statement

Course- R Programming >

In R programming, a normal looping sequence can be altered using the break or the next statement.

break statement

A break statement is used inside a loop to stop the iterations and flow the control outside of the loop. In a nested looping situation, where there is a loop inside another loop, this statement exits from the innermost loop that is being evaluated.

Syntax of break statement

break

Flowchart of break statement

R break statement flowchart

Example of break statement

x <- 1:5

for (val in x) {
    if (val == 3){
        break
    }
    print(val)
}

Output

[1] 1
[1] 2

In this example, we iterate over the vector x, which has consecutive numbers from 1 to 5. Inside the for loop we have used a condition to break if the current value is equal to 3. As we can see from the output, the loop terminates when it encounters the break statement.

next statement

 

 
 

A next statement is useful when we want to skip the current iteration of a loop without terminating it. On encountering next, the R parser skips further evaluation and starts next iteration of the loop.

Syntax of next statement

next

Flowchart of next statement

R next statement flowchart

Example of next statement

x <- 1:5

for (val in x) {
    if (val == 3){
        next
    }
    print(val)
}

Output

[1] 1
[1] 2
[1] 4
[1] 5

In the above example, we use the next statement inside a condition to check if the value is equal to 3. If the value is equal to 3, the current evaluation stops (value is not printed) but the loop continues with the next iteration. The output reflects this situation.